//
//  PublishViewController.swift
//  个人微博
//
//  Created by guo3920591 on 16/4/25.
//  Copyright © 2016年 guo3920591. All rights reserved.
//

import UIKit

import SVProgressHUD

import HMImagePicker

import HMEmoticon


private let GXLPicturetureCellID = "GXLPicturetureCellID"

class PublishViewController: UIViewController {
/// 视图生命周期
    override func viewDidLoad() {
        super.viewDidLoad()

        setupUI()
        
        //监听键盘变化
        
        NSNotificationCenter.defaultCenter().addObserver(self,
            selector: "keyboardChangeFrame:", name: UIKeyboardWillChangeFrameNotification, object: nil)
        
    }
    
    
    override func viewDidAppear(animated: Bool) {
        super.viewDidAppear(animated)
        //激活键盘
        textView.becomeFirstResponder()
        
    }
    
    override func viewWillDisappear(animated: Bool) {
        super.viewWillDisappear(animated)
        //退出键盘
        textView.resignFirstResponder()
    }

    override func didReceiveMemoryWarning() {
        super.didReceiveMemoryWarning()
        // Dispose of any resources that can be recreated.
    }
    
    
    deinit{
        //移除通知
        NSNotificationCenter.defaultCenter().removeObserver(self, name: UIKeyboardWillChangeFrameNotification, object: nil)
    }
    
// MARK: - 监听方法
    
    @objc private func keyboardChangeFrame(notifi: NSNotification){
        
      let  rect = (notifi.userInfo!["UIKeyboardFrameEndUserInfoKey"] as! NSValue).CGRectValue()
        
        let hight = rect.origin.y - UIScreen.mainScreen().bounds.height
       
        toolBar.snp_updateConstraints { (make) -> Void in
            
            make.bottom.equalTo(view).offset(hight)
        }
        
        //立刻布局
        
        UIView.animateWithDuration(0.25) { () -> Void in
            
            self.view.layoutIfNeeded()
        }
        
    }
/// 发送微博
    @objc private func didClickRightBtn(){
        //获取文本
        guard let text = textView.text else{
            
            return
        }
        
        
        if text.characters.count > 140 {
            
            SVProgressHUD.showInfoWithStatus("你发送的微博过长")
            
        }
        
        //发送微博
        
        NetworkTools.sharedTools.sendStatus(text,img: picturePlist.first) { (result) -> () in
        
            if result == nil {
                
                SVProgressHUD.showInfoWithStatus("发送失败")
                
                return
            }
            
            //返回
            
            dispatch_after(
                dispatch_time(DISPATCH_TIME_NOW, Int64(Double(NSEC_PER_SEC) * 1.0)),
                dispatch_get_main_queue(), { () -> Void in
                    
                    self.back()
            })
            
            
        }
        
        
    }
    
    @objc private func back(){
        self.dismissViewControllerAnimated(true, completion: nil)
    }
    /// 点击图片选择器
    @objc private func  selectPickerImage(){
        
        collectionView.hidden = false
        
        textView.updateTipLabelBottomConstraints(collectionView)
        
        textView.resignFirstResponder()
    }
    @objc private func selectEmjoyImage(){
        
     textView.useEmoticonInputView = !textView.useEmoticonInputView
    }
    
 
    
    // MARK: - 工具栏
    
    private func prepearToolBar(){
        //添加工具栏
        view.addSubview(toolBar)
        
        //设置约束
        
        toolBar.snp_makeConstraints { (make) -> Void in
            
            make.left.equalTo(view)
            make.right.equalTo(view)
            make.bottom.equalTo(view)
            make.height.equalTo(44)
            
            
        }
        
        //添加按钮
        let itemSettings2 = [["imageName": "compose_toolbar_picture", "actionName": "selectPickerImage"],
            ["imageName": "compose_mentionbutton_background"],
            ["imageName": "compose_trendbutton_background"],
            ["imageName": "compose_emoticonbutton_background", "actionName": "selectEmjoyImage"],
            ["imageName": "compose_add_background"]]
        
        //必须要初始化才能添加
        toolBar.items = [UIBarButtonItem]()
        
        for dict in  itemSettings2 {
            
            let imgName1 = dict["imageName"]
            
            let itemBtn = UIButton(gxl_title: nil,imgName: imgName1)
            
            if let imgFunction = dict["actionName"] {
                
                //监听工具栏的选择
                itemBtn.addTarget(self, action: Selector(imgFunction), forControlEvents: .TouchUpInside)
            }
            toolBar.items?.append(UIBarButtonItem(customView: itemBtn))
            
            toolBar.items?.append(UIBarButtonItem(barButtonSystemItem: .FlexibleSpace, target: nil, action: nil))
            
            
        }
        
        
        toolBar.items?.removeLast()
        
        
        
        
    }
    
    // MARK: - 准备文本
    
    private func prepearTextView(){
        //添加控件
        view.addSubview(textView)
        
        //自动布局
        
        textView.snp_makeConstraints { (make) -> Void in
            
            make.left.right.equalTo(view)
            
            make.top.equalTo(self.snp_topLayoutGuideBottom)
            
            make.bottom.equalTo(toolBar.snp_top)
            
        }
        
        //设置代理
        textView.delegate = self
        
        //设置最大长度
        textView.maxInputLength = 140
        
        textView.placeholder = "分享新鲜事..."
        
    }
    /// 准备图片视图
    private func prepearPictureView(){
        
        textView.addSubview(collectionView)
        
        collectionView.backgroundColor = UIColor.cz_colorWithHex(0xF5F5F5)
        
        //自动布局
        collectionView.snp_makeConstraints { (make) -> Void in
            
            make.top.equalTo(textView).offset(100)
            make.left.equalTo(view).offset(10)
            make.right.equalTo(view).offset(-10)
            make.height.equalTo(collectionView.snp_width)
            
        }
        
        //设置数据源和代理
        
        collectionView.dataSource = self
        
        collectionView.delegate = self
        
        //注册可重用cell
        collectionView.registerClass(GXlComposeViewCell.self, forCellWithReuseIdentifier: GXLPicturetureCellID)
        
        
        collectionView.hidden = true
        
        
        
    }
    
    
    /// 懒加载工具栏
    private lazy var toolBar: UIToolbar = UIToolbar()
    
    private lazy var rightButton: UIButton = {
        let rightButton = UIButton(gxl_title: "发送", titleColor: UIColor.whiteColor(), titleFont: 14, backImgName: "common_button_orange")
        //给按钮添加点击方法
        rightButton.addTarget(self, action: "didClickRightBtn", forControlEvents: .TouchUpInside)
        
        // 设置不同状态下的背景图
        rightButton.setBackgroundImage(UIImage(named: "common_button_white_disable"), forState: UIControlState.Disabled)
      // 设置不同状态的文字颜色
        rightButton.setTitleColor(UIColor.grayColor(), forState: UIControlState.Disabled)
        
        rightButton.frame.size = CGSize(width: 45, height: 28)
 
        return rightButton
    }()
    
    private lazy var titleView: UILabel = {
        
        let lb = UILabel()
        
        lb.numberOfLines = 0
        
        lb.textAlignment = .Center
        
        
        lb.font = UIFont.systemFontOfSize(14)
        
        if  let name = OAuthModel.shareUserAccount.name {
            
            let text = "发微博\n\(name)"
            
            let rang = (text as NSString).rangeOfString(name)
            
            let attrText = NSMutableAttributedString(string: text)
            
             attrText.addAttributes([NSForegroundColorAttributeName: UIColor.lightGrayColor(), NSFontAttributeName: UIFont.systemFontOfSize(12)], range: rang)
            
            
            lb.attributedText = attrText
            
            
            
        }else{
            
            lb.text = "发微博"
        }
    
        lb.sizeToFit()
        
        return lb
        
    }()
    
    private lazy var textView: HMEmoticonTextView = HMEmoticonTextView()
    
    
    private lazy var collectionView: UICollectionView = UICollectionView(frame: CGRectZero, collectionViewLayout: ComposePictureFlowLayout())
    
    private  lazy var picturePlist: [UIImage] = [UIImage]()
    
    /// 选中素材集合（通过素材集合可以和底层相册通讯）
    private var selectedAssets: [PHAsset]?
    
    //用户选择照片索引
    
    private  var selectImgIndex = 0

    
}

// MARK: - 私有类 图片视图布局
private class ComposePictureFlowLayout: UICollectionViewFlowLayout{
    
    private override func prepareLayout() {
        super.prepareLayout()
        
        let magin: CGFloat = 10
        
        let count: CGFloat = 3
        
        let width = (collectionView!.bounds.width - (count - 1)*magin) / count
        
        itemSize = CGSize(width: width, height: width)
        
        minimumInteritemSpacing = magin
        
        minimumLineSpacing = magin
        
        
    }
    
}

// MARK: - UITextViewDelegate
extension PublishViewController: UITextViewDelegate{
    /// 监听文本改变
  
    func textViewDidChange(textView: UITextView) {
        
        navigationItem.rightBarButtonItem?.enabled = textView.hasText()
        
    }
    
}

// MARK: - UICollectionViewDataSource,UICollectionViewDelegate
extension PublishViewController: UICollectionViewDataSource,UICollectionViewDelegate{
    func collectionView(collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
        
        
        
        return (picturePlist.count >= 5) ? picturePlist.count : picturePlist.count + 1
    
    
    }
    
    func collectionView(collectionView: UICollectionView, cellForItemAtIndexPath indexPath: NSIndexPath) -> UICollectionViewCell {
        
        let cell = collectionView.dequeueReusableCellWithReuseIdentifier(GXLPicturetureCellID, forIndexPath: indexPath) as! GXlComposeViewCell
        
        let image: UIImage? = (indexPath.item == picturePlist.count) ? nil : picturePlist[indexPath.item]
        
        cell.image = image
        
        //设置代理
        cell.delegate = self
        
        return cell
        
    }
    
    
}

extension PublishViewController: ComposeViewCellDelegte{
    /// 删除照片
   
    func composeViewCellDidRemovePicture(cell: GXlComposeViewCell) {
        
        let indexPath = collectionView.indexPathForCell(cell)!
        
        picturePlist.removeAtIndex(indexPath.item)
        
        collectionView.reloadData()
        
       
    }
    //添加照片
    func composeViewCellDidAddPicture(cell: GXlComposeViewCell) {
       
       selectImgIndex = collectionView.indexPathForCell(cell)!.item
        
        
        let picker = HMImagePickerController(selectedAssets: selectedAssets)
        
        picker.maxPickerCount = 5
        
        picker.pickerDelegate = self
        
//        picker.allowsEditing = true 
        
        presentViewController(picker, animated: true, completion: nil)
        
    }
    
    
}
// MARK: - HMImagePickerControllerDelegate
extension PublishViewController: HMImagePickerControllerDelegate{
    
    func imagePickerController(picker: HMImagePickerController, didFinishSelectedImages images: [UIImage], selectedAssets: [PHAsset]?) {
        
        self.picturePlist = images
        
        self.selectedAssets = selectedAssets
        
        collectionView.reloadData()

        
        dismissViewControllerAnimated(true, completion: nil)
        
    }
    
}

// MARK: - UIImagePickerControllerDelegate,UINavigationControllerDelegate
extension PublishViewController: UIImagePickerControllerDelegate,UINavigationControllerDelegate{
    
  func imagePickerController(picker: UIImagePickerController, didFinishPickingMediaWithInfo info: [String : AnyObject]) {
    
    
    
    let img = info["UIImagePickerControllerOriginalImage"] as! UIImage
    
    
    let width: CGFloat = 600
    
    let height = width * img.size.height / img.size.width
    
    
    img.cz_asyncDrawImage(CGSize(width: width, height: height)) { (image) -> () in
        
        if self.selectImgIndex >= self.picturePlist.count{
           
            self.picturePlist.append(image)
            
        }else{
            
            self.picturePlist[self.selectImgIndex] = image
            
        }
        
        
        
        self.collectionView.reloadData()
        
        self.dismissViewControllerAnimated(true, completion: nil)
        
    }
    
   
        
    }
   
}


// MARK: - 布局界面
extension PublishViewController{
    
    private func setupUI(){
        
        view.backgroundColor = UIColor.whiteColor()
        navigationItem.leftBarButtonItem = UIBarButtonItem(title: "取消", style: UIBarButtonItemStyle.Plain, target: self, action: "back")
        navigationItem.titleView = titleView
        navigationItem.rightBarButtonItem = UIBarButtonItem(customView: rightButton)
        navigationItem.rightBarButtonItem?.enabled = false
        
        //准备工具栏
        prepearToolBar()
        
        //准备textView文本
        prepearTextView()
        
        //准备图片视图
        prepearPictureView()
       
    }
    
}
